﻿package com.atn.edamame.tools 
{
    import flash.display.*;
	import flash.text.*;
	import flash.events.*;
	import mx.core.UIComponent;
	import mx.controls.Label;
	import com.atn.edamame.*;
	import mx.controls.TextInput;
	import com.adobe.xml.syndication.generic.*;
	import flash.net.*;

	public class Syndication extends EdamameControl
	{
		private var waitIndex:int = 90;	
		private var items:Array = new Array();
		private var loader:URLLoader;
		[Embed(source='../../../../pipe.png')]
		private var EmbedImage:Class;
		private var  valueInput:TextInput;
		private function enterFrameHandler(event:Event):void
		{
			waitIndex++;
			if ( waitIndex > 50 && edamameParent.drag == false)
			{
				if( items.length > 0 ){
					var item:IItem = items.shift();
					var o:EdamameString = new EdamameString();
					edamameParent.addEdamameObject(o);
					o.x = this.x;
					o.y = this.y + this.height ;
					o.value = item.title;
					o.vy = 2;
					waitIndex = 0;
				}else
				{
					loader.load( new URLRequest(EdamameConfig.getInstance().getProxyURL() + valueInput.text) );
					waitIndex = 0;
				}
			}
		}

		private function completeHandler(e:Event):void{
			var feed:IFeed = FeedFactory.getFeedByString(e.target.data);
			items = feed.items;
		}
		
        public override function init():void {
			var ui:UIComponent = new UIComponent();

			descriptionLabel = new Label();
            descriptionLabel.text = "Let's input RSS/ATOM URL here";
			descriptionLabel.width = 150;
			descriptionLabel.height = 20;
            addChild(descriptionLabel);
			descriptionLabel.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
			
			valueInput = new TextInput();
            valueInput.text = "http://twitter.com/statuses/user_timeline/4016461.atom";
			valueInput.width = 200;
			valueInput.height = 20;
            addChild(valueInput);
			
			var img:Bitmap = new EmbedImage() as Bitmap;
			ui.width = 100;
			ui.height = 30;
			ui.addChild(img);
			addChild(ui);
			
			ui.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
			this.height = 100;
			
			this.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
			loader = new URLLoader();
			loader.addEventListener( Event.COMPLETE, completeHandler );
			loader.load( new URLRequest(EdamameConfig.getInstance().getProxyURL() + valueInput.text) );
        }
		
		public override function destroy():void
		{
			removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
			super.destroy();
		}
	}
	
}